<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

</head>
<link href="../../css/calendar/jquery-ui-1.9.2.custom.css" rel="stylesheet" /><!-- 색상커스텀 -->
<link href='../../css/calendar/fullcalendar.css' rel='stylesheet' />
<link href='../../css/calendar/view_calendar.css' rel='stylesheet' />

<script src='../../js/Calendar/moment.min.js'></script>							 <!-- 시간설정플러그인 -->
<script src='../../js/Calendar/jquery.min.js'></script>							 <!-- 플러그인 -->
<script src='../../js/Calendar/jquery-ui.custom.min.js'></script>					 <!-- 달력설정메소드관련 -->
<script src='../../js/Calendar/fullcalendar.min.js'></script>				 <!-- 달력설정관련 -->
<script src='../../js/Calendar/lang-all.js'></script>		                 <!-- 언어 선택 -->
<%--  <script src='../../js/Calendar/view_calendar.js'></script>  --%>                 <!--  켈린더 이벤트 js -->
<script type="text/javascript">


$(document).ready(function() {
	
	var currentMousePos = {
		    x: -1,
		    y: -1
		};
	var currentLangCode = 'ko';
	//actually cursor position

	renderCalendar();
	initialise_event_generation();
	initialise_update_event();

	// build the language selector's options
    jQuery(document).on("mousemove", function (event) {
        currentMousePos.x = event.pageX;
        currentMousePos.y = event.pageY;
    });		
	$.each($.fullCalendar.langs, function(langCode) {
		$('#lang-selector').append(
			$('<option/>')
				.attr('value', langCode)
				.prop('selected', langCode == currentLangCode)
				.text(langCode)
		);
	});

	// rerender the calendar when the selected option changes
	$('#lang-selector').on('change', function() {
		if (this.value) {
			currentLangCode = this.value;
			$('#calendar').fullCalendar('destroy');
			renderCalendar();
		}
	});

	/* initialize the external events
	-----------------------------------------------------------------*/
	  function isElemOverDiv() {
        var trashEl = $('#calendarTrash');

        var ofs = trashEl.offset();

        var x1 = ofs.left;
        var x2 = ofs.left + trashEl.outerWidth(true);
        var y1 = ofs.top;
        var y2 = ofs.top + trashEl.outerHeight(true);

        if (currentMousePos.x >= x1 && currentMousePos.x <= x2 &&
            currentMousePos.y >= y1 && currentMousePos.y <= y2) {
            return true;
        }
        return false;
    }
	function renderCalendar() {
		$('#external-events .fc-event').each(function() {
			
			// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
			// it doesn't need to have a start or end
			var eventObject = {
				title: $.trim($(this).text()) // use the element's text as the event title
			};
			
			// store the Event Object in the DOM element so we can get to it later
			$(this).data('eventObject', eventObject);
			
			// make the event draggable using jQuery UI
			$(this).draggable({
				zIndex: 999,
				revert: true,      // will cause the event to go back to its
				revertDuration: 0  //  original position after the drag
			});
			
			
		});
	
		/* initialize the calendar
		-----------------------------------------------------------------*/
		$('#calendar').fullCalendar({
			header: {
				left: 'prev,next',
				center: 'title',
				right:'today'
				//right: 'month,agendaWeek,agendaDay'
			},
			allDayDefault: true,
			ignoreTimezone: true,
			defaultDate: new Date(),
			lang: currentLangCode,
			buttonIcons: true, // show the prev/next text
			weekNumbers: false,
			droppable: true, // this allows things to be dropped onto the calendar !!!
			dragRevertDuration: 0,
			editable: true,
			events: function(start, end,timezone, callback) {
				$.ajax({
		        	url: '../../jihoon/calendarList.action',
		        	dataType: 'JSON',
		            success: function(json) {
		            	 var events = [];
		                $.each(json.infoList,function(key, item){
		                    events.push({
		                        title : item.infoName,
		                        start : item.startDate,
		                        end : item.endDate,
		                        id : item.id,
		                        description : item.infoContent
		                    });
		                });
		                $.each(json.infoList2,function(key,item){
		                	events.push({
		                		title : item.infoName,
		                        start : item.startDate,
		                        end : item.endDate,
		                        id : item.id,
		                        description : item.infoContent
		                	});
		                });
		                callback(events);
		            }
		        });
		    },
			eventLimit: true, // allow "more" link when too many events
			eventDrop: function(event, delta, revertFunc,jsEvent) {
		        alert(event.title + " was dropped on " +event.start.format()+ event.end.format());
		        /* var email='<s:property value="#session.email" />'; */
		        var id = $(event).attr("id");
		        var startDate=event.start.format("YYYY-MM-DD hh:mm");
				var endDate=event.end.format("YYYY-MM-DD hh:mm");
				var email='aa@aa.co.kr';//나중에 세션에서 읽어올것.
				/* alert(id);
				alert(startDate);
				alert(endDate); */
		        if (confirm("Are you sure about this change?")) {
		            $.ajax({
			        	url:'../../jihoon/scheduleShift.action',
			        	type:'post',
			        	data:{startDate:startDate,endDate:endDate,id:id,email:email},
			        	dataType:'json',
			        	success:function(){
			        		$('#calendar').fullCalendar('refetchEvents');
			        	}
			        		//location.href="../../jsp/calendar/Calendar.jsp"
			           /*  success: function(json) {
			        		var template_event = $('#external_event_template').clone();
			        		var title = $('#txt_title').val();
			        		var description = $('#txt_description').val();

			        		//Edit id
			        		$(template_event).attr('id', get_uni_id());
			        		//Add template data attributes
			        		$(template_event).attr('data-title', title);
			        		$(template_event).attr('data-description', description);
			            }
 */			        });
		        }/* else{
		        	revertFunc();
		        } */
		        
		    },
			/* eventDragStart: function( event, jsEvent, ui, view ) { 
				
			}, */
			eventResize: function(event, delta, revertFunc) {
				 var id = $(event).attr("id");
					var endDate=event.end.format("YYYY-MM-DD hh:mm");
					var email='aa@aa.co.kr';//나중에 세션에서 읽어올것.
					/* alert(id);
					alert(endDate);
		        	alert(event.title + " end is now " + event.end.format()); */

		        if (!confirm("수정??")) {
		            revertFunc();
		        } else{
						$.ajax({
				        	url: '../../jihoon/scheduleScr.action',
				        	type:'post',
				        	data:{endDate:endDate,id:id,email:email},
				        	dataType:'json',
				            success: function(){
				            	$('#calendar').fullCalendar('refetchEvents');
				            }
				        });
						alert('수정 되었습니다');
				    }
			
		    },
 			eventDragStop: function (event, jsEvent, ui, view) {
 				var id = $(event).attr("id");
 				if (isElemOverDiv()) {
					if (confirm("정말로 삭제 하시겠습니까?")){
							$.ajax({
					        	url: '../../jihoon/scheduleDel.action',
					        	type:'post',
					        	data:{id:id},
					        	dataType: 'JSON',
					            success: function(){
					            	$('#calendar').fullCalendar('refetchEvents');
					            }
					        });
							alert('삭제 되었습니다');
					    }else{
						revertFunc();
					}
				}
			}, 
	   		eventClick: function(cal_event, js_event, view){
	   			calendar_event_clicked(cal_event, js_event, view);
			},
			drop: function(date) { // this function is called when something is dropped
				// retrieve the dropped element's stored Event Object
				external_event_dropped(date, this);
				if ($('#drop-remove').is(':checked')) {
					// if so, remove the element from the "Draggable Events" list
					$(this).remove();
				}
			}//drop
		});
		
	
}//rendercalendar
	 
	jQuery('.fc-toolbar').after('<div id="calendarTrash" class="calendar-trash">	<img src="../../image/Calendar/trashcan.png"></img></div>');//listens for drop event

});//end document
function external_event_dropped(date, external_event){
	//var originalEventObject = $(this).data('eventObject');
	// we need to copy it, so that multiple events don't have a reference to the same object
	/* var copiedEventObject = $.extend({}, originalEventObject); */
	// assign it the date that was reported
	var infoName = $(external_event).data('title');
	var infoContent = $(external_event).data("description");
	var start = date.format("YYYY-MM-DD hh:mm");
	var end=date.add('hour',23).format("YYYY-MM-DD hh:mm");
	var email='aa@aa.co.kr';//나중에 세션에서 읽어올것.
	/* alert(date);
	alert(infoName);
	alert(email);
	alert(start);
	alert("end"+end);
	alert(infoContent); */

	$.ajax({
    	url: '/mamma/jihoon/scheduleIns.action',
    	type:'post',
    	data:{infoName:infoName,infoContent:infoContent,startDate:start,endDate:end,email:email},
    	dataType: 'JSON',
        success:function(){
        	$('#calendar').fullCalendar('refetchEvents');
        }
    });
	alert("등록완료");
	/* copiedEventObject.start = date;
	copiedEventObject.id = get_uni_id();
	copiedEventObject.title = $(external_event).data('title');
	copiedEventObject.description = $(external_event).data('description'); */
	// render the event on the calendar
	// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
	//$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
	

}
function get_uni_id(){	//임시id
	//Generate unique id
	return new Date().getTime() + Math.floor(Math.random()) * 500;
}

function initialise_event_generation(){
	//Bind event
	$('#btn_gen_event').bind('click', function(){

		//Retrieve template event
		var template_event = $('#external_event_template').clone();
		var title = $('#txt_title').val();
		var description = $('#txt_description').val();

		//Edit id
		$(template_event).attr('id', get_uni_id());
		//Add template data attributes
		$(template_event).attr('data-title', title);
		$(template_event).attr('data-description', description);

		//Style external event
		
		//$(template_event).css('background-color', background_color);
		//$(template_event).css('border-color', border_color);
		//$(template_event).css('color', text_color);

		//Set text of external event
		$(template_event).text(title);
		
		//Append to external events container
		$('#external_events').append(template_event);

		//Initialise external event
		initialise_external_event('#' + $(template_event).attr('id'));

		//Show
		$(template_event).fadeIn(1000);
	});
}

function initialise_update_event(){
	
	$('#calendar').fullCalendar('clientEvents');
	//Bind event
	$('#btn_update_event').bind('click', function(){
		
		//Create vars
		var current_event_id = $('#txt_current_event').val();

		//Check if value found
		if(current_event_id){
			
			//Retrieve current event
			var current_event = $('#calendar').fullCalendar('clientEvents', current_event_id);
			//Check if found
			if(current_event && current_event.length == 1){
				alert("수정시작");
				var infoName = $('#txt_title').val();
				/* alert(infoName); */
				var infoContent = $('#txt_description').val();
			/* 	alert(infoContent); */
				var id=current_event_id;
				/* alert(id); */
				var email='aa@aa.co.kr';
				
					$.ajax({
				    	url: '/mamma/jihoon/scheduleUpd.action',
				    	type:'post',
				    	data:{infoName:infoName,infoContent:infoContent,id:id,email:email},
				    	dataType: 'JSON',
				        success: function(){
				        	$('#calendar').fullCalendar('refetchEvents');
				        }
				    });
/* 
				//Retrieve current event from array
				current_event = current_event[0];

				//Set values

				current_event.title = $('#txt_title').val();
				current_event.description = $('#txt_description').val();


				//Update event
				$('#calendar').fullCalendar('updateEvent', current_event); */
			}
		}
	});
}

function initialise_event_generation(){

	//Bind event
	$('#btn_gen_event').bind('click', function(){

		//Retrieve template event
		var template_event = $('#external_event_template').clone();
		var title = $('#txt_title').val();
		var description = $('#txt_description').val();


		//Edit id
		$(template_event).attr('id', get_uni_id());
		//Add template data attributes
		$(template_event).attr('data-title', title);
		$(template_event).attr('data-description', description);


		//Style external event
		/*
		$(template_event).css('background-color', background_color);
		$(template_event).css('border-color', border_color);
		$(template_event).css('color', text_color);
*/
		//Set text of external event
		$(template_event).text(title);
		
		//Append to external events container
		$('#external_events').append(template_event);

		//Initialise external event
		initialise_external_event('#' + $(template_event).attr('id'));

		//Show
		$(template_event).fadeIn(1000);
	});
}
function initialise_external_event(selector){

	//Initialise booking types
	$(selector).each(function(){

		//Make draggable
		$(this).draggable({
			revert: true,
			revertDuration: 0,
			zIndex: 999,
			cursorAt: {
				left: 1,
				top: 1
			}
		});

		//Create event object
		var event_object = {
			title: $.trim($(this).text())
			};

		//Store event in dom to be accessed later
		$(this).data('eventObject', event_object);
	});
}
function calendar_event_clicked(cal_event, js_event, view){

	//Set generation values
	set_event_generation_values(cal_event.id,cal_event.title, cal_event.description);
}


/* Set event generation values */
function set_event_generation_values(id,  title, description){
	//Set values
	$('#txt_title').val(title);
	$('#txt_description').val(description);
	$('#txt_current_event').val(id);
}

</script>
<style>	
	#top {
		background: #eee;
		border-bottom: 1px solid #ddd;
		padding: 0 10px;
		line-height: 40px;
		font-size: 12px;
	}	
	#wrap {
		width: 1100px;
		margin: 0 auto;
	}
		
	#external-events {
		float: left;
		width: 150px;
		padding: 2px 10px;
		border: 1px solid #ccc;
		background: #eee;
		text-align: left;
	}
		
	#external-events h4 {
		font-size: 16px;
		margin-top: 0;
		padding-top: 1em;
	}
		
	#external-events .fc-event {
		margin: 4px 0;
		cursor: pointer;
	}


	#calendar {
		float: right;
		width: 850px;
	}
	#calendarTrash {
		float: right;
	}
</style>
</head>
<body>
	<div id='top'>

		Language:
		<select id='lang-selector'></select>

	</div>
	<div id='wrap'>
		<div id='calendar'></div>
			<div id="event_generation_wrapper">
				 
				<input id='txt_title' type='text' value='Title' /><br />
				<textarea id='txt_description'>Description</textarea><br />
				<input id="btn_gen_event" type="button" value="New Event" class='btn' />
				<input id="btn_update_event" type="button" value="Update Event" class='btn'/>
				<input id="txt_current_event" type="hidden" value="" />
				
			</div>
		<div id='external-events'>
			<h4>Draggable Events</h4>
			
			<div id='external_events'>
				<div id='external_event_template' class='fc-event'>One Hour</div>
			</div>			
			
			<p>
				<input type='checkbox' id='drop-remove' />
				<label for='drop-remove'>remove after drop</label>
			</p>
		</div>

		<div style='clear:both'></div>
		
	</div>
	
</body>
</html>
